package com.qingsong.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.mybatisflex.core.query.QueryChain;
import com.mybatisflex.core.query.RelationsBuilder;
import com.mybatisflex.core.update.UpdateChain;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.qingsong.constant.ML;
import com.qingsong.dto.SeckillInsertDTO;
import com.qingsong.dto.SeckillPageDTO;
import com.qingsong.dto.SeckillUpdateDTO;
import com.qingsong.entity.Article;
import com.qingsong.entity.Seckill;
import com.qingsong.exception.ServiceException;
import com.qingsong.mapper.SeckillDetailMapper;
import com.qingsong.mapper.SeckillMapper;
import com.qingsong.service.SeckillService;
import com.qingsong.vo.SeckillSimpleListVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.mybatisflex.core.paginate.Page;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.List;

import static com.mybatisflex.core.query.QueryMethods.curDate;
import static com.mybatisflex.core.query.QueryMethods.date;
import static com.qingsong.entity.table.ArticleTableDef.ARTICLE;
import static com.qingsong.entity.table.CourseTableDef.COURSE;
import static com.qingsong.entity.table.SeckillDetailTableDef.SECKILL_DETAIL;
import static com.qingsong.entity.table.SeckillTableDef.SECKILL;

/**
 * 秒杀表 服务层实现。
 *
 * @author qingsong
 * @since 2024-12-22
 */
@Service
@CacheConfig(cacheNames = "seckill")
public class SeckillServiceImpl extends ServiceImpl<SeckillMapper, Seckill>  implements SeckillService{
    @Autowired
    private SeckillDetailMapper seckillDetailMapper;
    @CacheEvict(allEntries = true)
    @Override
    public boolean insert(SeckillInsertDTO dto) {
        // 组装 entity 实体类
        Seckill seckill = BeanUtil.copyProperties(dto, Seckill.class);
        // 判断生效时间和失效时间是否合理
        if (dto.getStartTime().isAfter(dto.getEndTime())) {
            throw new ServiceException("生效时间不能在失效时间之后");
        }
        //标题查重
        if(QueryChain.of(mapper).where(SECKILL.TITLE.eq(dto.getTitle())).exists()){
            throw new ServiceException("秒杀标题已存在") ;
        }
        seckill.setCreated(LocalDateTime.now());
        seckill.setUpdated(LocalDateTime.now());
        return mapper.insert(seckill) > 0;
    }

    @Cacheable(key = "#p0", condition = "#p0 != null", unless = "#result == null")
    @Override
    public Seckill select(Long id) {
        return mapper.selectOneWithRelationsById(id);
    }

    @Cacheable(key = "#root.methodName", unless = "#result == null")
    @Override
    public List<SeckillSimpleListVO> simpleList() {
        return QueryChain.of(mapper)
                .withRelations()
                .listAs(SeckillSimpleListVO.class);
    }

    @Cacheable(key = "#root.methodName + ':' + #p0.toString()", condition = "#p0 != null", unless = "#result == null")
    @Override
    public Page<Seckill> page(SeckillPageDTO dto) {
        QueryChain<Seckill> queryChain = QueryChain.of(mapper)
                .orderBy(SECKILL.ID.asc());

        // title 条件
        String title = dto.getTitle();
        if (ObjectUtil.isNotNull(title)) {
            queryChain.where(SECKILL.TITLE.like(title));
        }
        return queryChain.withRelations().page(new Page<>(dto.getPageNum(), dto.getPageSize()));
    }

    @Cacheable(key = "#root.methodName", unless = "#result == null")
    @Override
    public List<Seckill> top(Long n) {
        return QueryChain.of(mapper)
                .orderBy(SECKILL.ID.desc())
                .limit(n)
                .withRelations()
                .list();
    }

    @Cacheable(key = "#root.methodName + ':' + #p0",
            condition = "#p0 != null",
            unless = "#result == null")
    @Override
    public List<Seckill> near(Long n) {
        return QueryChain.of(mapper)
                .where(date(SECKILL.START_TIME).eq(curDate()))
                .orderBy(SECKILL.START_TIME.asc())
                .limit(n)
                .withRelations()
                .list();
    }
    @CacheEvict(allEntries = true)
    @Override
    public boolean update(SeckillUpdateDTO dto) {
        // 组装 entity 实体类
        Seckill seckill = BeanUtil.copyProperties(dto, Seckill.class);
        // 判断生效时间和失效时间是否合理
        if (dto.getStartTime().isAfter(dto.getEndTime())) {
            throw new ServiceException("生效时间不能在失效时间之后");
        }
        seckill.setTitle(seckill.getTitle());
        seckill.setUpdated(LocalDateTime.now());
        return UpdateChain.of(seckill).where(SECKILL.ID.eq(seckill.getId())).update();
    }

    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(allEntries = true)
    @Override
    public boolean delete(Long id) {
        // 按秒杀主键删除秒杀明细记录
        UpdateChain.of(seckillDetailMapper)
                .where(SECKILL_DETAIL.FK_SECKILL_ID.eq(id))
                .remove();
        // 按秒杀主键删除一条秒杀记录
        return mapper.deleteById(id) > 0;
    }

    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(allEntries = true)
    @Override
    public boolean deleteBatch(List<Long> ids) {
        // 按秒杀主键批量删除秒杀明细记录
        UpdateChain.of(seckillDetailMapper)
                .where(SECKILL_DETAIL.FK_SECKILL_ID.in(ids))
                .remove();
        // 按秒杀主键批量删除秒杀记录
        return mapper.deleteBatchByIds(ids) > 0;
    }

}
